/*****************************************************************************************
 **  Author:jxx 2022
 **  QQ:283591387
 **完整文档见：http://v2.volcore.xyz/document/api 【代码生成页面ViewGrid】
 **常用示例见：http://v2.volcore.xyz/document/vueDev
 **后台操作见：http://v2.volcore.xyz/document/netCoreDev
 *****************************************************************************************/
//此js文件是用来自定义扩展业务代码，可以扩展一些自定义页面或者重新配置生成的代码
import modelHeader from "../goods_inventory_warehouse_xm/goodsInventoryWarehouse_xm.vue"
import gridHeader from "@/components/print/selectTemplet.vue"
let extension = {
  components: {
    //查询界面扩展组件
    gridHeader,
    gridBody: '',
    gridFooter: '',
    //新建、编辑弹出框扩展组件
    modelHeader,
    modelBody: '',
    modelFooter: ''
  },
  tableAction: '', //指定某张表的权限(这里填写表名,默认不用填写)
  buttons: {
    view: [],
    box: [],
    detail: []
  }, //扩展的按钮
  methods: {
    //下面这些方法可以保留也可以删除
    async onInit() { //框架初始化配置前，
      //示例：在按钮的最前面添加一个按钮
      //   this.buttons.unshift({  //也可以用push或者splice方法来修改buttons数组
      //     name: '按钮', //按钮名称
      //     icon: 'el-icon-document', //按钮图标vue2版本见iview文档icon，vue3版本见element ui文档icon(注意不是element puls文档)
      //     type: 'primary', //按钮样式vue2版本见iview文档button，vue3版本见element ui文档button
      //     onClick: function () {
      //       this.$Message.success('点击了按钮');
      //     }
      //   });

      //示例：设置修改新建、编辑弹出框字段标签的长度
      // this.boxOptions.labelWidth = 150;
      this.queryFields = ['WHSE_name_out', 'CreateDate']
      let startTime = this.base.getOneWeekAgoDate()
      let endTime = this.base.getDate(false) + " 23:59:59"
      this.searchFormFields.CreateDate = [startTime, endTime]
      if (this.$route.path == "/q_warehouse_add_allot" && JSON.stringify(this.$route.query) != '{}') {
        console.log("触发查询")
        await this.base.setSearchParamFn(this)
        // this.searchFormFields.Coding = null
        // this.searchFormFields.WHSE_name_out = null
        // this.searchFormFields.WHSE_name_in = null
        // this.searchFormFields.AuditStatus = null
        // this.searchFormFields.Goods_num = [null, null]
        // this.searchFormFields.CreateDate = [null, null]
        // const selectList = ['Coding',]
        // this.searchFormOptions.forEach(item => {
        //   item.forEach(x => {
        //     if (!selectList.includes(x.field)) {
        //       x.onChange = (v) => {
        //         this.$route.query = {}
        //       }
        //     }
        //   })
        // })
        setTimeout(() => {
          this.refresh()
        })
      }
    },
    onInited() {
      console.log("onInited");
      //框架初始化配置后
      //如果要配置明细表,在此方法操作
      //this.detailOptions.columns.forEach(column=>{ });
      this.textInline = false
      this.detailOptions.textInline = false
      // this.setFiexdSearchForm(true);
      // this.buttons.forEach(item => {
      //   if (item.name == "高级查询") {
      //     item.hidden = true
      //   }
      // })

      let indexNum = this.detailOptions.buttons.findIndex(item => item.name == "添加行")
      if (indexNum != "-1") {
        this.detailOptions.buttons.splice(indexNum, 1)
      }
      this.detailOptions.buttons.unshift({
        name: "选择商品", //按钮名称
        icon: 'el-icon-plus', //按钮图标，参照iview图标
        type: 'primary',
        plain: true,
        onClick: function () { //触发事件
          if (this.rowschild && this.$refs.detail.rowData.length) {
            this.rowschild.click()
          }
          // const WHSE_name_out_val = JSON.stringify(this.editFormFields.WHSE_name_out)
          // if (WHSE_name_out_val == "[]" || WHSE_name_out_val == "null") {
          if (!this.editFormFields.WHSE_name_out) {
            this.base.ElMessageFn('请选择调出机构')
            return;
          }
          // const WHSE_name_in_val = JSON.stringify(this.editFormFields.WHSE_name_in)
          // if (WHSE_name_in_val == "[]" || WHSE_name_in_val == "null") {
          if (!this.editFormFields.WHSE_name_in) {
            this.base.ElMessageFn('请选择调入机构')
            return;
          }
          if (!this.editFormFields.Ja_ja_lv && this.editFormFields.Ja_ja_lv !== 0) {
            this.base.ElMessageFn('请输入加价率')
            return;
          }
          this.$store.commit("setTabelText", true)
          // this.$refs.modelHeader.open(this.editFormFields.WHSE_name_out[this.editFormFields.WHSE_name_out.length - 1])
          this.$refs.modelHeader.open(this.editFormFields.WHSE_name_out, this.editFormFields.Ja_ja_lv)
        }
      })
      this.detailOptions.columns.forEach(x => {
        if (x.field == 'WHSE_name_in') {
          x.filter = false
        }
      })
      // //明细表点击表格时触发编辑方法
      this.detailOptions.beginEdit = (row, column, index) => {
        if (this.$route.path != "/q_warehouse_add_allot" || this.rowAuditStatus != 0) { //|| !this.CreateUserBoole
          console.log("this.rowAuditStatus", this.rowAuditStatus);
          return false
        }
        // const WHSE_name_in_val = JSON.stringify(this.editFormFields.WHSE_name_in)
        // if (WHSE_name_in_val == "[]" || WHSE_name_in_val == "null") {
        if (!this.editFormFields.WHSE_name_in) {
          this.base.ElMessageFn('请选择调入机构')
          return false;
        }
        /*
        if (this.currentAction != 'Add' && !this.statusOff) {
          return false
        }
        //------test 限制同一用户编辑
        if (this.currentAction == 'Add') {
          //可以继续
        } else if (this.currentAction == 'Update' && !this.statusOff || !this.user_id_boole) {
          return false
        }
        //------test 限制同一用户编辑---end*/
        let rows = document.querySelectorAll(".grid-detail .el-table__body .el-table__row")
        this.rowschild = rows[0].childNodes[2]
        setTimeout(() => {
          // 调出数量
          let testInputDom = rows[index].querySelectorAll("td")[6].querySelector("input")
          if (testInputDom) {
            testInputDom.addEventListener("keyup", (e) => {
              if (!+e.target.value && e.target.value != undefined) {
                row.Total_price = ""
                row.Tax_exclusive_exWarehouse_total_price = ""
                this.base.ElMessageFn("数量请输入有效数字")
                return
              }
              if (!+row.Goods_price && row.Goods_price != undefined) {
                row.Total_price = ""
                this.base.ElMessageFn("调入价格请输入有效数字")
                return
              }
              if (row.AvailableQuantity < +e.target.value) {
                this.base.ElMessageFn('数量大于可用数量')
              }
              if (row.Goods_price) {
                let num = e.target.value * row.Goods_price
                row.Total_price = this.base.roundToFourDecimals(num)
              }
              if (row.Tax_exclusive) {
                let num = e.target.value * row.Tax_exclusive
                row.Tax_exclusive_exWarehouse_total_price = this.base.roundToFourDecimals(num)
              }
              // if (+testInputDom.value) {
              //   if (row.AvailableQuantity < +e.target.value) {
              //     this.base.ElMessageFn('调出数量大于可用数量')
              //   }
              // } else {
              //   this.base.ElMessageFn('请出入数字')
              // }
            })
          }
          // 调出价格
          let priceDom = rows[index].querySelectorAll("td")[7].querySelector("input")
          if (priceDom) {
            priceDom.addEventListener("keyup", (e) => {
              if (!+e.target.value && e.target.value != undefined) {
                row.Total_price = ""
                this.base.ElMessageFn("调入价格请输入有效数字")
                return
              }
              if (!+row.Goods_num && row.Goods_num != undefined) {
                row.Total_price = ""
                this.base.ElMessageFn("数量请输入有效数字")
                return
              }
              if (row.Goods_num) {
                let num = e.target.value * row.Goods_num
                row.Total_price = this.base.roundToFourDecimals(num)
              }
              // if (+priceDom.value) {
              //   console.log("row.Goods_num", +row.Goods_num);
              //   if (row.Goods_num) {
              //     if (!+row.Goods_num) {
              //       this.base.ElMessageFn('调出数量请填写数字')
              //       return;
              //     }
              //     row.Total_price =this.base.roundToFourDecimals(row.Goods_num * priceDom.value)
              //   }
              // } else {
              //   this.base.ElMessageFn('请出入数字')
              // }
            })
          }
        }, 0)

        this.detailOptions.columns.forEach(item => {
          if (item.field == "WHSE_name_in") {
            if (!row.Goods_sub) {
              return
            }
            // this.base.getWHSEName(item, row.Goods_sub, false, this.editFormFields.WHSE_name_in[this.editFormFields.WHSE_name_in.length - 1])
            this.base.getWHSEName(item, row.Goods_sub, false, this.editFormFields.WHSE_name_in)
          }
        })

        return true
      }
    },
    onActivated() {
      console.log("onActivated", onActivated)
    },
    WHSE_IdDisableFn() {
      this.editFormOptions.forEach(item => {
        item.forEach(x => {
          if (x.field == 'WHSE_name_out' || x.field == 'WHSE_name_in') {
            x.disabled = true
          }
        })
      })
    },
    async searchBefore(param) {
      // console.log(this.searchFormOptions)
      //界面查询前,可以给param.wheres添加查询参数
      //返回false，则不会执行查询
      if (this.$route.path == "/q_warehouse_add_allot" && JSON.stringify(this.$route.query) != '{}') {
        await this.base.setSearchBefore(this, "Add_allot", param)
        // this.searchFormOptions.forEach(item => {
        //   item.forEach(x => {
        //     console.log("x.range",x.range)
        //     const field = x.field
        //     if (x.type == "like") {
        //       if (this.searchFormFields[field]) {
        //         param.wheres = param.wheres.filter(item => item.name != "Add_allot")
        //         this.$route.query = {}
        //       }
        //     }
        //     if ( x.range||x.type == "range") {
        //       const sectionState = ["[null,null]",JSON.stringify(["",null]),JSON.stringify([null,""]),JSON.stringify(["",""])]
        //       const dateState=sectionState.includes(JSON.stringify(this.searchFormFields[field]))
        //       if (!dateState) {
        //         param.wheres = param.wheres.filter(item => item.name != "Add_allot")
        //         this.$route.query = {}
        //         console.log("时间")
        //       }
        //     }
        //   })
        // })
        // const sectionState = ["[null,null]", JSON.stringify(["", null]), JSON.stringify([null, ""]), JSON.stringify(["", ""])]
        // const dateState = sectionState.includes(JSON.stringify(this.searchFormFields.CreateDate))
        // if (this.searchFormFields.Coding || !dateState) {
        //   param.wheres = param.wheres.filter(item => item.name != "Add_allot")
        //   this.$route.query = {}
        // }
      }
      return true;
    },
    searchAfter(result) {
      //查询后，result返回的查询数据,可以在显示到表格前处理表格的值
      // console.log("result", result);
      result.forEach(item => {
        if (item.Ja_ja_lv !== null) {
          item.Ja_ja_lv += "%"
        }
      })
      return true;
    },
    addBefore(formData) {
      //新建保存前formData为对象，包括明细表，可以给给表单设置值，自己输出看formData的值
      return this.testAdd(formData);
    },
    updateBefore(formData) {
      //编辑保存前formData为对象，包括明细表、删除行的Id
      return this.testAdd(formData);
    },
    rowClick({
      row,
      column,
      event
    }) {
      //查询界面点击行事件
      this.$refs.table.$refs.table.toggleRowSelection(row); //单击行时选中当前行;
    },
    detailRowClick({
      row,
      column,
      event
    }) {
      this.$refs.detail.$refs.table.toggleRowSelection(row);
      if (this.$route.path != "/q_warehouse_add_allot" || this.rowAuditStatus != 0) {
        return
      } //|| !this.CreateUserBoole
      if (column.property == "Goods_num" || column.property == "Goods_price" || column.property == "WHSE_name_in" || column.property == "Remark") {
        let dom = event.target
        if (dom.nodeName != "SPAN") {
          setTimeout(() => {
            let inpDom = dom.querySelector("input")
            inpDom.focus()
          }, 0)
        }
      }
    },
    delDetailRow(rows) { //弹出框删除明细表的行数据(只是对table操作，并没有操作后台)
      try {
        if (rows.length == this.$refs.detail.rowData.length) {
          this.$store.commit("setWHSE_time", true)
          this.$store.commit("setWHSE_disabled", true)
          this.WHSE_Interval = setInterval(() => {
            console.log("WHSE_Interval", this.WHSE_Interval)
            this.editFormOptions.forEach(item => {
              item.forEach(x => {
                if (x.field == 'WHSE_name_out' || x.field == 'WHSE_name_in') {
                  if (this.$store.state.WHSE_disabled) {
                    x.disabled = true
                  } else {
                    x.disabled = false
                  }
                }
              })
            })
            if (!this.$store.state.WHSE_time) {
              clearInterval(this.WHSE_Interval)
              console.log("WHSE_Interval清除", this.WHSE_Interval)
            }
          }, 500)
        }
      } catch {
        console.log("删除catch", )
      }
      return true;
    },
    onModelClose(iconClick) {
      //iconClick=true为点击左中上角X触发的关闭事件
      //如果返回 false不会关闭弹出框 
      //return false;
      // this.storeRemoveForm()
      this.$store.commit("setTabelText", true)
      this.boxModel = false;
    },
    async modelOpenBefore(row) {
      this.$store.commit("setTabelText", false)
      this.CreateUserBoole = row.CreateID == this.$store.state.userID
      this.rowAuditStatus = await row.AuditStatus
      if (JSON.stringify(row) == "{}") {
        this.rowAuditStatus = 0
        this.CreateUserBoole = true
      }
      if (this.$route.path != "/q_warehouse_add_allot" || this.rowAuditStatus != 0) { //|| !this.CreateUserBoole
        this.boxButtons[0].hidden = true
        this.detailOptions.buttons.forEach(item => {
          if (item.name != "导出" && item.name != "刷新") {
            item.hidden = true
          }
        })
      } else {
        this.boxButtons[0].hidden = false
        this.detailOptions.buttons.forEach(item => item.hidden = false)
      }
    },
    modelOpenAfter(row) {
      if (this.currentAction!='Add'&&row.Ja_ja_lv !== null) {
        this.editFormFields.Ja_ja_lv = row.Ja_ja_lv.replace(/%/g, "");
      }
      //点击编辑、新建按钮弹出框后，可以在此处写逻辑，如，从后台获取数据
      //(1)判断是编辑还是新建操作： this.currentAction=='Add';
      //(2)给弹出框设置默认值
      //(3)this.editFormFields.字段='xxx';
      //如果需要给下拉框设置默认值，请遍历this.editFormOptions找到字段配置对应data属性的key值
      //看不懂就把输出看：console.log(this.editFormOptions)
      this.editFormOptions.forEach(item => {
        item.forEach(x => {
          if (x.field == "Ja_ja_lv") {
            // x.extra = {
            //   text: "%",
            //   style: "color:#a8abb2;font-size:28px;cursor:default;position:absolute;right:50px;top:3px",
            // }
            try {
              // x.blur = () => {
              //   console.log("失焦");
              // }
              // console.log("x", x);
              x.onChange = (val) => {
                // console.log("change", val);
                this.$refs.detail.rowData.forEach(item => {
                  item.Goods_price = this.base.roundToFourDecimals(item.CostPrice * (1 + (val / 100)))
                  let num =item.Goods_num * item.Goods_price
                  item.Total_price = this.base.roundToFourDecimals(num)
                })
              }
            } catch (error) {
              console.error(error);
            }
          }
          if (x.field == "Remark" || x.field == "WHSE_name_out" || x.field == "WHSE_name_in" || x.field == "Tax_rate" || x.field == "Ja_ja_lv") {
            x.disabled = false
          } else {
            x.disabled = true
          }
          if (this.currentAction != 'Add' && (x.field == "WHSE_name_out" || x.field == "WHSE_name_in" || x.field == "Tax_rate" || x.field == "Ja_ja_lv")) {
            x.disabled = true
          }
          if (this.$route.path != "/q_warehouse_add_allot" || this.rowAuditStatus != 0) { //|| !this.CreateUserBoole
            x.disabled = true
          }
        })
      })
    },
    testAdd(formData) {
      console.log("formData", formData);
      if (this.currentAction == "Add") {
        formData.mainData.Goods_num = 0
        formData.mainData.Total_price = 0
      }
      if (!this.$refs.detail.rowData.length) {
        this.base.ElMessageFn('明细表不可为空', "error")
        return false
      }
      // let boole = formData.detailData.some(item => item.Goods_num <= 0 || item.Goods_num == null)
      // let booleP = formData.detailData.every(item => item.Goods_price > 0 && +item.Goods_price)
      // let booleP2 = formData.detailData.every(item => +item.Goods_price == true || item.Goods_price > 0)
      // let boole = formData.detailData.every(item => item.Goods_num > 0 && +item.Goods_num)

      // if (!boole) {
      //   this.base.ElMessageFn("加价调拨明细中数量请大于零")
      //   return false;
      // }
      // if (!booleP) {
      //   this.base.ElMessageFn("加价调拨明细中商品调出价格请大于零")
      //   return false;
      // }
      // if (!booleP2) {
      //   this.base.ElMessageFn("加价调拨明细中调出价格请填写有效数字")
      //   return false;
      // }
      let boole2 = formData.detailData.some(item => +item.Goods_num === 0)
      if (boole2) {
        this.base.ElMessageFn("明细表中数量不可为零")
        return false;
      }
      if (!this.editFormFields.Tax_rate) {
        this.base.ElMessageFn("请选择税率")
        return false;
      }
      let boole = formData.detailData.some(item => item.Goods_num == "" || item.Goods_num == null || item.Goods_num == undefined)
      if (boole) {
        this.base.ElMessageFn("明细表中请填写数量")
        return false;
      }
      let boole3 = formData.detailData.every(item => +item.Goods_num > 0 && +item.Goods_num)
      if (!boole3) {
        this.base.ElMessageFn("明细表中数量请填写有效正数")
        return false;
      }

      let boole22 = formData.detailData.some(item => +item.Goods_price === 0)
      if (boole22) {
        this.base.ElMessageFn("明细表中调入价格不可为零")
        return false;
      }
      let boole1 = formData.detailData.some(item => item.Goods_price == "" || item.Goods_price == null || item.Goods_price == undefined)
      if (boole1) {
        this.base.ElMessageFn("明细表中请填写调入价格")
        return false;
      }
      let boole33 = formData.detailData.every(item => +item.Goods_price > 0 && +item.Goods_price)
      if (!boole33) {
        this.base.ElMessageFn("明细表中调入价格请填写有效正数")
        return false;
      }
      let boole4 = formData.detailData.some(item => +item.Goods_num > +item.AvailableQuantity)
      if (boole4) {
        this.base.ElMessageFn("明细表中数量大于可用数量")
        return false;
      }
      let booleP3 = formData.detailData.every(item => item.WHSE_name_in)
      if (!booleP3) {
        this.base.ElMessageFn("加价调拨明细中请选择调入库位")
        return false;
      }
      return true
    },
  }
};
export default extension;